<?php
declare (strict_types = 1);
namespace app\admin\model\user;

use app\common\model\BaseModel;
use app\admin\logic\user\Account;

/**
 * 定义用户登录授权token
 */
class Token extends BaseModel
{
    /**
     * 表名
     * @var string
     */
    protected $name = 'admin_user_token';

    /**
     * 设置自动写入时间
     * @var boolean
     */
    protected $autoWriteTimestamp = true;

    /**
     * 无需创建时间
     * @var boolean
     */
    protected $createTime = false;
    /**
     * 定义字段类型
     * @var array
     */
    protected $type = [
        'id' => 'integer',
    ];

    /**
     * 定义表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 全局查询范围
     * @var [type]
     */
    protected $globalScope = ['device_type'];

    /**
     * 定义查询设备类型范围条件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-10
     * @param    [type]                         $query [description]
     * @return   [type]                                [description]
     */
    public function scopeDeviceType($query)
    {
        $query->where('device_type', request()->device_type);
    }

    /**
     * 当前token关联的用户
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-10
     * @return   app\user\logic\user\Account
     */
    public function user()
    {
        return $this->belongsTo(Account::class,'admin_user_id');
    }

    /**
     * 新增数据事件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-03-10
     * @return   string
     */
    public static function onBeforeInsert($token)
    {
        $token->device_type = request()->device_type;
    }
}
